const Qs = require("querystring");
const axios = require("axios");
import { Toast } from "vant";
import hub, { SERVICE_EXCEPTION, TIMEOUT } from "./hub";

const http = axios.create({
  baseURL: window.path,
  timeout: 30000,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
  },
  transformRequest: (params) => Qs.stringify(params),
});

export default http;

//拦截请求
http.interceptors.request.use((config) => {
  // 处理config
  return config;
});

//拦截响应
http.interceptors.response.use(
  // 成功 : err.code >=200 || err.code <=300
  function(res) {
    const body = res.data;

    if (body.status != 1) {
      if (body.msg) {
        Toast.fail(body.msg);
      }
      return Promise.reject();
    }

    //处理服务器返回的数据
    return Promise.resolve(body);
  },

  // 失败: status > 300
  function(err) {
    if (err.code === "ECONNABORTED") {
      hub.emit(TIMEOUT);
    }
    if (err.response) {
      const res = err.response;
      if (res.status == "500") {
        hub.emit(SERVICE_EXCEPTION);
      }
    }
    if (err == "Error: Network Error") {
      Toast("网络连接失败，请检查网络设置");
    }
    return Promise.reject();
  }
);
